package com.top4create.webapp.controller;

import org.apache.commons.lang.StringUtils;
import com.top4create.service.GenericManager;
import com.top4create.model.Type;
import com.top4create.webapp.controller.BaseFormController;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

@Controller
@RequestMapping("/typeform")
public class TypeFormController extends BaseFormController {
	private GenericManager<Type, Long> typeManager = null;

	@Autowired
	public void setTypeManager(
			@Qualifier("typeManager") GenericManager<Type, Long> typeManager) {
		this.typeManager = typeManager;
	}

	public TypeFormController() {
		setCancelView("redirect:/types");
		setSuccessView("redirect:/types");
	}

	@ModelAttribute
	@RequestMapping(value = "", method = { RequestMethod.GET,
			RequestMethod.POST })
	protected Type showForm(HttpServletRequest request) throws Exception {
		String id = request.getParameter("id");

		if (!StringUtils.isBlank(id)) {
			return typeManager.get(new Long(id));
		}

		return new Type();
	}

	@RequestMapping(value = "/submit", method = RequestMethod.POST)
	public String onSubmit(Type type, BindingResult errors,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (request.getParameter("cancel") != null) {
			return getCancelView();
		}

		log.debug("entering 'onSubmit' method...");

		boolean isNew = (type.getId() == null);
		String success = getSuccessView();
		Locale locale = request.getLocale();

		if (request.getParameter("delete") != null) {
			typeManager.remove(type.getId());
			saveMessage(request, getText("type.deleted", locale));
		} else {
			typeManager.save(type);
			String key = (isNew) ? "type.added" : "type.updated";
			saveMessage(request, getText(key, locale));

			if (!isNew) {
				success = "redirect:/typeform?id=" + type.getId();
			}
		}

		return success;
	}
}
